/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/LimitImpl.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: LimitImpl.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.limit;

/**
 * @author elancom
 * @date Apr 11, 2012
 */
public class LimitImpl implements Limit, InitialTotalSupport, LimitConstants {
	protected int pageSize = PAGE_SIZE;

	protected int curPage = 0;

	protected int firstResult = 0;

	protected int totalResults = 0;

	public LimitImpl() {
		super();
	}

	public LimitImpl(int curPage, int pageSize) {
		super();
		this.curPage = curPage;
		this.pageSize = pageSize;
	}

	@Override
	public int getCurPage() {
		return curPage;
	}

	@Override
	public int getFirstResult() {
		if (firstResult == 0) {
			firstResult = (curPage - 1) * pageSize;
			firstResult = firstResult < 0 ? 0 : firstResult;
		}
		return firstResult;
	}

	public int getMaxResults() {
		return pageSize;
	}

	public int getNextPage() {
		return (curPage < getTotalPage() ? curPage + 1 : curPage);
	}

	@Override
	public int getPageSize() {
		return pageSize;
	}

	public int getPrevPage() {
		return (curPage > 1 ? curPage - 1 : curPage);
	}

	public int getTotalPage() {
		return (totalResults % pageSize == 0 ? totalResults / pageSize : totalResults / pageSize + 1);
	}

	@Override
	public int getTotalResults() {
		return totalResults;
	}

	public LimitImpl setCurPage(int curPage) {
		this.curPage = curPage;
		return this;
	}

	public LimitImpl setFirstResult(int firstResult) {
		this.firstResult = firstResult;
		return this;
	}

	public LimitImpl setPageSize(int pageSize) {
		this.pageSize = pageSize;
		return this;
	}

	@Override
	public void setTotalResults(int totalResults) {
		curPage = (curPage < 1 ? 1 : ((curPage - 1) * pageSize > totalResults ? getTotalPage() : curPage));
		this.totalResults = totalResults;
	}
}
